package cn.caskm.souvenirshopsystem.service.impl;

import cn.caskm.souvenirshopsystem.constants.BizConstants;
import cn.caskm.souvenirshopsystem.domain.Result;
import cn.caskm.souvenirshopsystem.domain.dto.PageDTO;
import cn.caskm.souvenirshopsystem.domain.po.Goods;
import cn.caskm.souvenirshopsystem.domain.po.GoodsCollect;
import cn.caskm.souvenirshopsystem.domain.query.MyCollectQuery;
import cn.caskm.souvenirshopsystem.domain.query.PageQuery;
import cn.caskm.souvenirshopsystem.domain.vo.MyCollectVO;
import cn.caskm.souvenirshopsystem.exceptions.BizException;
import cn.caskm.souvenirshopsystem.mapper.GoodsCollectMapper;
import cn.caskm.souvenirshopsystem.mapper.GoodsMapper;
import cn.caskm.souvenirshopsystem.service.GoodsCollectService;
import cn.caskm.souvenirshopsystem.utils.UserContext;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class GoodsCollectServiceImpl extends ServiceImpl<GoodsCollectMapper, GoodsCollect> implements GoodsCollectService {

    private final GoodsMapper goodsMapper;

    @Override
    public Result<PageDTO<GoodsCollect>> page(PageQuery query) {
        // 获取参数
        Long pageNum = query.getPageNum();
        if (pageNum == null) {
            pageNum = BizConstants.DEFAULT_PAGE_NUM;
        }
        Long pageSize = query.getPageSize();
        if (pageSize == null) {
            pageSize = BizConstants.DEFAULT_PAGE_SIZE;
        }

        // 查询数据
        Page<GoodsCollect> page = lambdaQuery()
                .orderByDesc(GoodsCollect::getCollectTime)
                .page(new Page<>(pageNum, pageSize));

        List<GoodsCollect> records = page.getRecords();
        return Result.success(PageDTO.of(records, page.getPages(), page.getTotal()));
    }

    @Override
    public Result<List<GoodsCollect>> getAll() {
        List<GoodsCollect> list = lambdaQuery()
                .orderByDesc(GoodsCollect::getCollectTime)
                .list();
        return Result.success(list);
    }

    @Override
    public Result<GoodsCollect> detail(Integer id) {
        GoodsCollect goodsCollect = getById(id);
        if (goodsCollect == null) {
            throw new BizException("收藏信息不存在");
        }
        return Result.success(goodsCollect);
    }

    @Override
    public void saveOrUpdateEntity(GoodsCollect goodsCollect) {
        if (goodsCollect.getCollectId() == null) {
            // 新增收藏
            goodsCollect.setCollectTime(LocalDateTime.now());
            save(goodsCollect);
        } else {
            // 修改收藏
            updateById(goodsCollect);
        }
    }

    @Override
    public void collectGoods(Integer goodsId) {
        // 获取登录用户
        Long userId = UserContext.getUser();

        // 查询收藏记录
        GoodsCollect record = lambdaQuery()
                .eq(GoodsCollect::getUserId, userId.intValue())
                .eq(GoodsCollect::getGoodsId, goodsId)
                .one();
        if (record == null) {
            // 没收藏
            record = new GoodsCollect();
            record.setGoodsId(goodsId);
            record.setUserId(userId.intValue());
            record.setCollectTime(LocalDateTime.now());
            save(record);
        } else {
            removeById(record.getCollectId());
        }
    }

    @Override
    public Result<PageDTO<MyCollectVO>> goodsCollectService(MyCollectQuery query) {
        // 获取登录用户
        Long userId = UserContext.getUser();

        // 分页查询信息
        Long pageNum = query.getPageNum();
        Long pageSize = query.getPageSize();
        String goodsName = query.getGoodsName();
        Page<GoodsCollect> page = lambdaQuery()
                .eq(GoodsCollect::getUserId, userId.intValue())
                .page(new Page<>(pageNum, pageSize));
        List<GoodsCollect> records = page.getRecords();
        if (CollUtil.isEmpty(records)) {
            return Result.success(PageDTO.empty());
        }

        // 查询商品信息
        Set<Integer> goodsIds = records.stream().map(GoodsCollect::getGoodsId).collect(Collectors.toSet());
        List<Goods> goods = goodsMapper.selectByIds(goodsIds);
        if (CollUtil.isEmpty(goods)) {
            throw new BizException("商品信息为空");
        }
        Map<Integer, Goods> goodsMap = goods.stream().collect(Collectors.toMap(Goods::getGoodsId, g -> g));

        // 组装vo
        List<MyCollectVO> result = records.stream()
                .map(item -> {
                    MyCollectVO vo = new MyCollectVO();
                    vo.setId(item.getCollectId());
                    Integer goodsId = item.getGoodsId();
                    Goods currentGood = goodsMap.get(goodsId);
                    vo.setGoodsId(goodsId);
                    vo.setGoodsName(currentGood.getGoodsName());
                    vo.setStock(currentGood.getSellStatus());
                    vo.setPrice(currentGood.getGoodsPrice());
                    vo.setPicture(currentGood.getImage());
                    vo.setDesc(currentGood.getGoodsDesc());
                    return vo;
                })
                .filter(item -> StrUtil.isBlank(goodsName) || item.getGoodsName().contains(goodsName))
                .collect(Collectors.toList());

        return Result.success(PageDTO.of(result, page.getPages(), page.getTotal()));
    }
}
